package com.yc.videocache.file;

import com.yc.videocache.ProxyCacheUtils;
import com.yc.videocache.TextUtils;

/**
 * Implementation of {@link FileNameGenerator} that uses MD5 of url as file name
 */

/**
 * LruDiskUsage
 *
 * @since 2021-05-10
 */
public class Md5FileNameGenerator implements FileNameGenerator {
    private static final int MAX_EXTENSION_LENGTH = 4;

    @Override
    public String generate(String url) {
        String extension = getExtension(url);
        String name = ProxyCacheUtils.computeMD5(url);

        return TextUtils.isEmpty(extension) ? name : name + "." + extension;
    }

    private String getExtension(String url) {
        int dotIndex = url.lastIndexOf('.');
        int slashIndex = url.lastIndexOf('/');
        final int len = -1;
        final int lene = 2;
        return dotIndex != len && dotIndex > slashIndex && dotIndex + lene + MAX_EXTENSION_LENGTH > url.length()
            ? url.substring(dotIndex + 1, url.length()) : "";
    }
}
